package com.mall.pay.services;

import com.alipay.demo.trade.Main;
import com.alipay.demo.trade.utils.ExceptionProcessorUtils;
import com.mall.order.OrderQueryService;
import com.mall.order.dto.MyOrderDetailResponse;
import com.mall.order.dto.OrderDetailRequest;
import com.mall.order.dto.OrderItemDto;
import com.mall.pay.PayService;
import com.mall.pay.constant.PayRetCode;
import com.mall.pay.dto.PayCodeRequest;
import com.mall.pay.dto.PayCodeResponse;
import com.mall.pay.dto.QueryPayResponse;
import com.mall.pay.dto.QueryPayStatusRequest;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author
 * @date 2020/12/24 15:33
 */
@Service(interfaceClass = PayService.class)
@Component
public class PayServiceImpl implements PayService {
    @Autowired
    Main main;
    @Reference(timeout = 3000,check = false)
    OrderQueryService orderQueryService;

    @Override
    public PayCodeResponse getPayCode(PayCodeRequest request) {
        PayCodeResponse payCodeResponse = new PayCodeResponse();
        OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
        orderDetailRequest.setOrderId(request.getOrderId());
        MyOrderDetailResponse myOrderDetailResponse = orderQueryService.queryOrderDetail(orderDetailRequest);
        //订单中商品详情
        List<OrderItemDto> goodsList = myOrderDetailResponse.getMyOrderDetailInfo().getGoodsList();
        String qrCode = main.test_trade_precreate(request, goodsList);
        if (qrCode == null) {
            payCodeResponse.setCode(PayRetCode.SYSTEM_ERROR.getCode());
            payCodeResponse.setMsg(PayRetCode.SYSTEM_ERROR.getMessage());
            return payCodeResponse;
        }
        payCodeResponse.setCode(PayRetCode.SUCCESS.getCode());
        payCodeResponse.setMsg(PayRetCode.SUCCESS.getMessage());
        payCodeResponse.setQrCode(qrCode);
        return payCodeResponse;
    }

    @Override
    public QueryPayResponse queryStatus(QueryPayStatusRequest request) {
        QueryPayResponse queryPayResponse = new QueryPayResponse();
        String orderId = request.getOrderId();
        OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
        orderDetailRequest.setOrderId(orderId);
        MyOrderDetailResponse orderDetail = orderQueryService.queryOrderDetail(orderDetailRequest);
        try {
            queryPayResponse = main.test_trade_query(orderDetail,orderId);
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(queryPayResponse,e);
        }
        return queryPayResponse;
    }
}
